import random
import string
from typing import Iterable, List, Union


def safe_iterable(list: Union[List[str], None]) -> Iterable[str]:
    """确保输入总是可迭代的，即使它为None"""
    return list if list is not None else []


def str_to_list(data: str) -> List[str]:
    """将字符串转换为列表"""
    if "," in data:
        return data.split(",")
    else:
        return [data]


def list_to_str(list: List[str]) -> str:
    """将列表转换为字符串"""
    return ",".join(list)


def set_to_list(set: Union[set, None]) -> List[str]:
    """将集合转换为列表"""
    return list(set) if set is not None else []


def set_to_str(set: Union[set, None]) -> str:
    """将集合转换为字符串"""
    return list_to_str(set_to_list(set))


def str_to_set(srt: str) -> set:
    """将字符串转换为集合"""
    return set(str_to_list(srt))


def generate_string(length: int = 8) -> str:
    """
    生成随机字符串
    :param length: 字符串长度
    """
    return ''.join(random.sample(string.ascii_letters + string.digits, length))


def to_lower_camel(string: str) -> str:
    '''
    将连字符串转换为驼峰式字符串 首字符小写 to_camel->toCamel
    '''
    words = string.split('_')
    if not words:
        return ''
    # 首单词小写
    first_word = words[0].lower()
    # 后续单词首字母大写
    remaining_words = [word.capitalize() for word in words[1:]]
    # 拼接结果
    return first_word + ''.join(remaining_words)


def to_camel(string: str) -> str:
    '''
    将连字符串转换为驼峰式字符串 首字符也大写 to_camel->ToCamel
    '''
    return ''.join(word.capitalize() for word in string.split('_'))
